/**
 * Copyright (C) Skywares Information Technology, LTD. 
 * All Rights Reserved.
 *
 * TestFilter.java created on 2020年2月18日 下午5:58:01 by Lyon Lu 
 */
package com.mvc.server.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.sleuth.instrument.web.TraceWebServletAutoConfiguration;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import brave.propagation.ExtraFieldPropagation;
import lombok.extern.log4j.Log4j2;

/**
 * <pre>
 * Description:
 * 
 * @author Lyon Lu
 * @date 2020年2月18日 下午5:58:01
 *
 * </pre>
 */
@Log4j2
@Component
@Order(TraceWebServletAutoConfiguration.TRACING_FILTER_ORDER + 1)
public class PropagatingExtraFieldsFilter extends GenericFilterBean{

	public static final String clientIdKey = "clientId";
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		String sleuthClientId = ExtraFieldPropagation.get(clientIdKey);
		
		if (StringUtils.isNotBlank(sleuthClientId)) {
			log.info("sleuth propagating clientId: " + sleuthClientId);
			chain.doFilter(request, response);
			return;
		}
		
		String reqClientId = ((HttpServletRequest) request).getHeader(clientIdKey);
		
		if (StringUtils.isNotBlank(reqClientId)) {
			
			ExtraFieldPropagation.set(clientIdKey, reqClientId.trim());
			log.info("request header clientId: " + reqClientId);
		}
		
        chain.doFilter(request, response);
	}

}
